package uk.co.biggroup.lotto.syndicate;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.apache.http.client.ClientProtocolException;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import org.xml.sax.SAXException;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class Numbers extends ListActivity {

	public static final String PREFS_NAME = "Settings";
	private static ArrayList<DrawNumbers> itemsy;
	public static int error;

	static DrawNumbers[] drawsArr;
	static String balance;
	static String lastUpdate;
	static String luckynumbers;
	static String status;
	static String date;
	static String acTextStatus;
	static int acstatus;
	static int numberOfSets;
	static int type;
	
	TextView statusstatus;
	TextView drawdate;	
	TextView no1;
	TextView no2;
	TextView no3;
	TextView no4;
	TextView no5;
	TextView no6;
	TextView no7;
	ImageView icon6;
	RelativeLayout ballsset;
	
	LuckyNumbers lnumber;
	public static String link;
	public static int drawid;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.numbers);

		Bundle bundle = this.getIntent().getExtras();
		
		drawid = bundle.getInt("drawid");
		link = Integer.toString(drawid);

		acstatus = bundle.getInt("acstatus");
		type = bundle.getInt("type");
		acTextStatus = bundle.getString("acTextStatus");
		balance = bundle.getString("balance");
		lastUpdate = bundle.getString("lastupdate");
		luckynumbers = bundle.getString("luckynumbers");		
		status = bundle.getString("status");
		date = bundle.getString("date");

		ballsset = (RelativeLayout) this.findViewById(R.id.ballsset);
		
		if (type == 2) {
			icon6 = (ImageView) this.findViewById(R.id.icon6);
			icon6.setImageResource(R.drawable.ball_aqua_icon);
		}
		
		if (luckynumbers.length() == 0) {
			ballsset.setVisibility(View.GONE);
			luckynumbers = "00,00,00,00,00,00,00";
		} else {
			ballsset.setVisibility(View.VISIBLE);
		}
		
		lnumber = new LuckyNumbers(luckynumbers);
		
		statusstatus = (TextView) this.findViewById(R.id.statusstatus);
		drawdate = (TextView) this.findViewById(R.id.drawdate);
		
		no1 = (TextView) this.findViewById(R.id.no1);
		no2 = (TextView) this.findViewById(R.id.no2);
		no3 = (TextView) this.findViewById(R.id.no3);
		no4 = (TextView) this.findViewById(R.id.no4);
		no5 = (TextView) this.findViewById(R.id.no5);
		no6 = (TextView) this.findViewById(R.id.no6);
		no7 = (TextView) this.findViewById(R.id.no7);

		no1.setText(lnumber.getNO1());
		no2.setText(lnumber.getNO2());
		no3.setText(lnumber.getNO3());
		no4.setText(lnumber.getNO4());
		no5.setText(lnumber.getNO5());
		no6.setText(lnumber.getNO6());
		no7.setText(lnumber.getNO7());

		drawdate.setText(date + " ");
		statusstatus.setText(status + " ");
		
		new DownloadNumbers().execute("");

	}

	class IconicAdapter extends ArrayAdapter<DrawNumbers> {

		private ArrayList<DrawNumbers> itemsy;

		IconicAdapter(Context context, int textViewResourceId,
				ArrayList<DrawNumbers> itemsyx) {
			super(context, textViewResourceId, itemsyx);
			this.itemsy = itemsyx;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = getLayoutInflater();
			View drawitem = inflater.inflate(R.layout.numbersitem, parent, false);
			TextView matches = (TextView) drawitem.findViewById(R.id.matches);
			TextView counter = (TextView) drawitem.findViewById(R.id.counter);
			TextView no1 = (TextView) drawitem.findViewById(R.id.no1);
			TextView no2 = (TextView) drawitem.findViewById(R.id.no2);
			TextView no3 = (TextView) drawitem.findViewById(R.id.no3);
			TextView no4 = (TextView) drawitem.findViewById(R.id.no4);
			TextView no5 = (TextView) drawitem.findViewById(R.id.no5);
			TextView no6 = (TextView) drawitem.findViewById(R.id.no6);
			
			ImageView icon = (ImageView) drawitem.findViewById(R.id.icon);
			ImageView icon2 = (ImageView) drawitem.findViewById(R.id.icon2);
			ImageView icon3 = (ImageView) drawitem.findViewById(R.id.icon3);
			ImageView icon4 = (ImageView) drawitem.findViewById(R.id.icon4);
			ImageView icon5 = (ImageView) drawitem.findViewById(R.id.icon5);
			ImageView icon6 = (ImageView) drawitem.findViewById(R.id.icon6);

			ImageView star = (ImageView) drawitem.findViewById(R.id.star);

			DrawNumbers d = itemsy.get(position);
			if (d != null) {
				int matchCounter = 0;
				no1.setText(d.getNO1());
				if (lnumber.comp(d.getNO1(), matchCounter)) {
					icon.setImageResource(R.drawable.ball_red_icon);
					matchCounter++;
				}
				no2.setText(d.getNO2());
				if (lnumber.comp(d.getNO2(), matchCounter)) {
					icon2.setImageResource(R.drawable.ball_red_icon);
					matchCounter++;
				}				
				no3.setText(d.getNO3());
				if (lnumber.comp(d.getNO3(), matchCounter)) {
					icon3.setImageResource(R.drawable.ball_red_icon);
					matchCounter++;
				}
				no4.setText(d.getNO4());
				if (lnumber.comp(d.getNO4(), matchCounter)) {
					icon4.setImageResource(R.drawable.ball_red_icon);
					matchCounter++;
				}
				no5.setText(d.getNO5());
				if (lnumber.comp(d.getNO5(), matchCounter)) {
					icon5.setImageResource(R.drawable.ball_red_icon);
					matchCounter++;
				}
				no6.setText(d.getNO6());
				if (lnumber.comp(d.getNO6(), matchCounter)) {
					icon6.setImageResource(R.drawable.ball_red_icon);
					matchCounter++;
				}				
				counter.setText(d.getCounter());
				matches.setText(Integer.toString(matchCounter));
				if(matchCounter >= 3) {
					star.setVisibility(View.VISIBLE);
				}
			}
			return (drawitem);
		}
	}
	
	private class DownloadNumbers extends AsyncTask<String, Void, String> {

		ProgressDialog dialog;

		@Override
		protected String doInBackground(String... params) {
			error = 0;
			try {
				getHtml();
			} catch (ClientProtocolException e) {
				Logh.i("ClientProtocolException");
			} catch (IOException e) {
				Logh.i("IOException");
			} catch (XPatherException e) {
				Logh.i("XPatherException");
			} catch (ParserConfigurationException e) {
				Logh.i("ParserConfigurationException");
			} catch (SAXException e) {
				Logh.i("SAXException");
			} catch (XPathExpressionException e) {
				Logh.i("XPathExpressionException");
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			dialog.dismiss();

			if (error == 1) {
				Intent intent = new Intent();
				intent.setClass(Numbers.this, Draws.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
				finish();
			}

			Numbers.this.setListAdapter(new IconicAdapter(Numbers.this,
					R.layout.numbersitem, itemsy));
		}

		@Override
		protected void onPreExecute() {
			dialog = ProgressDialog.show(Numbers.this, "",
					"Wait, Accessing data...", true);
		}

		@Override
		protected void onProgressUpdate(Void... values) {

		}

		public void getHtml() throws ClientProtocolException, IOException,
				XPatherException, ParserConfigurationException, SAXException,
				IOException, XPatherException, XPathExpressionException {

			String NUMBERS_XPATH = "//draws/draw[@id='" + link + "']/lines//line/@numbers";
			String ERROR_XPATH = "//error/@msg";
			
			TagNode node;

			ArrayList<String> numbersList = new ArrayList<String>();

			SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
			String tokenCheck = settings.getString("token", "");
			
			String fullurl = "http://syndicates.biggroup.co.uk/MyAccount/DownloadXML.aspx?t=" + tokenCheck;
			Logh.i(fullurl);
			URL url = new URL(fullurl);
			URLConnection conn = url.openConnection();

			HtmlCleaner cleaner = new HtmlCleaner();
			CleanerProperties props = cleaner.getProperties();
			props.setAllowHtmlInsideAttributes(true);
			props.setAllowMultiWordAttributes(true);
			props.setRecognizeUnicodeChars(true);
			props.setTranslateSpecialEntities(true);
			props.setOmitComments(true);

			node = cleaner.clean(new InputStreamReader(conn.getInputStream()));
					
			Object[] numbers_nodes = node.evaluateXPath(NUMBERS_XPATH);
			Object[] error_nodes = node.evaluateXPath(ERROR_XPATH);
			
			if (error_nodes.length > 0) {
				for (Object linkNode : error_nodes) {
					String s = linkNode.toString();
					error = 1;
					Logh.i(s);
				}
			}
				
			if (numbers_nodes.length > 0) {
				for (Object linksNode : numbers_nodes) {
					String s = linksNode.toString();
					numbersList.add(s);
					Logh.i(s);
				}
			}

			itemsy = new ArrayList<DrawNumbers>();
			int itemCount = numbersList.size();
			numberOfSets = itemCount;
			drawsArr = new DrawNumbers[itemCount];
			for (int i = 0; i < itemCount; i++) {
				Logh.i("LOOPh");
				drawsArr[i] = new DrawNumbers(numbersList.get(i), i+1);
				itemsy.add(drawsArr[i]);
			}
		}

	}

	
	
}
